package com.cellulam.framework.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Slf4j
public final class NumberUtil {

    public static final double round(Double value, int scale) {
        BigDecimal v;
        if (value == null) {
            v = BigDecimal.ZERO;
        } else {
            v = new BigDecimal(value);
        }
        return v.setScale(scale, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     * 默认取两位小数四舍五入
     *
     * @param value
     * @return
     */
    public static final String format(double value) {
        return format(value, 2);
    }

    public static final String format(double value, int scale) {
        return format(value, scale, RoundingMode.HALF_UP);
    }

    public static final String format(double value, int scale, RoundingMode mode) {
        BigDecimal bigDecimal = new BigDecimal(value);
        return String.valueOf(bigDecimal.setScale(scale, mode).doubleValue());
    }

    public static final Integer parseInt(String value) {
        return parseInt(value, null);
    }

    public static final Integer parseInt(String value, Integer defaultValue) {
        try {
            return StringUtils.isEmpty(value) ? defaultValue : Integer.parseInt(value);
        } catch (Exception e) {
            log.warn("", e);
        }
        return defaultValue;
    }

    public static final Long parseLong(String value) {
        return parseLong(value, null);
    }

    public static final Long parseLong(String value, Long defaultValue) {
        try {
            return StringUtils.isEmpty(value) ? defaultValue : Long.parseLong(value);
        } catch (Exception e) {
            log.warn("", e);
        }
        return defaultValue;
    }
}
